package com.grsu.phonestation.web;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.grsu.phonestation.domain.Client;
import com.grsu.phonestation.domain.EnrolleePayment;
import com.grsu.phonestation.domain.Payment;
import com.grsu.phonestation.service.EnrolleePaymentService;
import com.grsu.phonestation.service.PaymentService;

@Controller
@RequestMapping("/payments")
public class PaymentController {

	@Autowired
	@Qualifier("paymentServiceImpl")
	private PaymentService<Payment> paymentService;

	@Autowired
	@Qualifier("enrolleePaymentServiceImpl")
	private EnrolleePaymentService enrolleePaymentService;

	@RequestMapping(value = "/search", method = { RequestMethod.POST })
	public ModelAndView login(
			@RequestParam(value = "sum", required = true) Double sum,
			@RequestParam(value = "metodPayment", required = true) String metodPayment,
			HttpServletRequest request, HttpSession session) {

		ModelAndView mav = new ModelAndView();

		Object userObject = session.getAttribute("user");
		if ((userObject != null) && (userObject instanceof Client)) {

			Client user = (Client) userObject;

			if (sum != null && metodPayment != null) {

				EnrolleePayment enrolleePayment = new EnrolleePayment();

				Date date = new Date();

				enrolleePayment.setSum(sum);
				enrolleePayment.setUser(user);
				enrolleePayment.setMethodPayment(metodPayment);
				enrolleePayment.setDateActivation(date.toString());

				enrolleePaymentService.addPayment(enrolleePayment);

				mav.addObject("user", user);
				mav.addObject("enrolleePayment", enrolleePayment);
				mav.setViewName("payments");
			}
			
		}

		return mav;
	}
	
	@RequestMapping(value = { "/", " " }, method = { RequestMethod.GET })
	public ModelAndView home(HttpSession session, Model model) {

		ModelAndView mav = new ModelAndView();

		Object userObject = session.getAttribute("user");
		if ((userObject != null) && (userObject instanceof Client)) {

			Client user = (Client) userObject;

			List<Payment> payments = paymentService.getPaymentsClient(user);

			mav.addObject("user", user);
			mav.addObject("payments", payments);
			mav.setViewName("payments");
		} else {
			mav = new ModelAndView("redirect:/login");
			mav.setViewName("login");
		}

		return mav;
	}

	

}
